package com.rt.code.generator.freemarker;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.converts.MySqlTypeConvert;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import com.rt.code.generator.freemarker.exec.FreemarkerGen;
import com.rt.easyjava.base.biz1.bean.TmptUserSetting;
import com.rt.easyjava.base.biz1.mapper.TmptUserSettingMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author wuxiaoyong
 * @version 1.0.1
 * mybatis-plus 动态生成器
 */
@Service
@Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
public class MpGeneratorEnums {

    @Resource
    private FreemarkerGen freemarkerGen;

    @Resource
    private TmptUserSettingMapper tmptUserSettingMapper;

    @Value("${mybatis-plus.generator.path.java}")
    private String outputDirProj;
    @Value("${mybatis-plus.generator.module}")
    private String module;

    private String outputDirMain;
    private String javaDir;
    private String packagePath;
    private String enumsOutputDir;

    private String outputVueDirProj;
    private String outputDirViewEnumsOption;

    @Value("${spring.datasource.username}")
    private String username;
    @Value("${spring.datasource.password}")
    private String password;
    @Value("${spring.datasource.url}")
    private String jdbc_url;
    @Value("${spring.datasource.driver}")
    private String jdbc_driver;

    public static void main(String[] args) {
        ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
        MpGeneratorComplex mpGeneratorComplex = (MpGeneratorComplex) ctx.getBean("mpGeneratorComplex");
        String _keyRandom = "t_logs_urlprop_85777706";
        // mpGenerator.execute(_keyRandom, null);
    }

    private void initPath(String _userIdStr){
        // 从config中取数据
        /*ResourceBundle resourceBundle = ResourceBundle.getBundle("config");
        outputDirProj = resourceBundle.getString("mybatis-plus.generator.path");*/

        // 数据库中有的话，以数据库中为准
        Long _userId = Long.parseLong(_userIdStr);
        TmptUserSetting tmptUserSettingParam = new TmptUserSetting();
        tmptUserSettingParam.setCreatemanId(_userId);
        tmptUserSettingParam.setDeleteflag(0);
        QueryWrapper queryWrapper = new QueryWrapper(tmptUserSettingParam);
        List<TmptUserSetting> tmptUserSettingList = tmptUserSettingMapper.selectList(queryWrapper);
        for (TmptUserSetting tmptUserSetting : tmptUserSettingList) {
            String name = tmptUserSetting.getName();
            String value = tmptUserSetting.getValue();
            if ("mybatis-plus.generator.path".equalsIgnoreCase(name)) {
                outputDirProj = value;
                continue;
            }
            if ("mybatis-plus.generator.vue.path".equalsIgnoreCase(name)) {
                outputVueDirProj = value;
                continue;
            }
        }

        module = "common";
        outputDirMain = outputDirProj+File.separator+module+File.separator+"src"+File.separator+"main"+File.separator;
        javaDir = "java"+File.separator;
        packagePath = "com/rt/easyjava/common/";
        enumsOutputDir = outputDirMain + javaDir + packagePath  + "/enums/";

        //outputVueDirProj = resourceBundle.getString("mybatis-plus.generator.vue.path");
        outputDirViewEnumsOption =  outputVueDirProj+File.separator+"views"+File.separator+"coding"+File.separator+"components"+File.separator+"enums";

       /* username = resourceBundle.getString("druid.username");
        password = resourceBundle.getString("druid.password.plain");
        jdbc_url = resourceBundle.getString("druid.url");
        jdbc_driver = resourceBundle.getString("druid.driver");*/
    }


    public void execute(String _userId) {
        execute(null, _userId);
    }

    public void execute(Long id, String _userId) {
        initPath(_userId);

        AutoGenerator mpg = new AutoGenerator();
        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        gc.setOutputDir(outputDirMain + javaDir);
        gc.setFileOverride(true);
        gc.setActiveRecord(true);// 开启 activeRecord 模式
        gc.setEnableCache(false);// XML 二级缓存
        gc.setBaseResultMap(true);// XML ResultMap
        gc.setBaseColumnList(true);// XML columList
        gc.setDateType(DateType.ONLY_DATE);

        /**
         * 此处设置生成人名字
         */
        gc.setAuthor("wuxiaoyong");

        // 自定义文件命名，注意 %s 会自动填充表实体属性！
        gc.setMapperName("%sMapper" );
        gc.setXmlName("%sMapper" );
        gc.setServiceName("%sService" );
        gc.setServiceImplName("%sServiceImpl" );
        gc.setControllerName("%sController" );
        gc.setSwagger2(true);
        mpg.setGlobalConfig(gc);
        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setDbType(DbType.MARIADB);
        dsc.setTypeConvert(new MySqlTypeConvert());
        dsc.setDriverName(jdbc_driver);
        dsc.setUsername(username);
        dsc.setPassword(password);
        dsc.setUrl(jdbc_url);
        mpg.setDataSource(dsc);

        gen(gc, mpg, id);
    }

    private void gen(GlobalConfig gc, AutoGenerator mpg, Long id){

        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        // strategy.setCapitalMode(true);// 全局大写命名
        // strategy.setDbColumnUnderline(true);//全局下划线命名
//		strategy.setTablePrefix(new String[] { "bmd_", "mp_" });// 此处可以修改为您的表前缀
        strategy.setNaming(NamingStrategy.underline_to_camel);// 表名生成策略
        /*strategy.setInclude(new String[]{"org_charge_bill","org_charge_bill_detail"});*/ // 需要生成的表
        //strategy.setInclude(new String[]{"test_logs_urlprop"});
        // strategy.setExclude(new String[]{"test"}); // 排除生成的表
        // 自定义实体父类
        // strategy.setSuperEntityClass("com.baomidou.demo.TestEntity");
        // 自定义实体，公共字段
        // strategy.setSuperEntityColumns(new String[] { "test_id", "age" });
        // 自定义 mapper 父类
        // strategy.setSuperMapperClass("com.baomidou.demo.TestMapper");
        // 自定义 service 父类
        // strategy.setSuperServiceClass("com.baomidou.demo.TestService");
        // 自定义 service 实现类父类
        // strategy.setSuperServiceImplClass("com.baomidou.demo.TestServiceImpl");
        // 自定义 controller 父类
        //strategy.setSuperControllerClass("com.runtong.agri.web.controller.BaseController" );
        // 【实体】是否生成字段常量（默认 false）
        // public static final String ID = "test_id";
        // strategy.setEntityColumnConstant(true);
        // 【实体】是否为构建者模型（默认 false）
        // public User setName(String name) {this.name = name; return this;}
        // strategy.setEntityBuliderModel(true);
        mpg.setStrategy(strategy);

        // 包配置
        PackageConfig pc = new PackageConfig();
        pc.setModuleName(null);  //所属模块
        pc.setParent("com.rt.easyjava.common" ); // 自定义包路径
        pc.setController("controller"); // 这里是控制器包名，默认 web
        pc.setEntity("entity" );
        pc.setXml("mapper" );
        pc.setMapper("mapper" );
        pc.setService("service.intf" );
        pc.setServiceImpl("service.impl" );
        mpg.setPackageInfo(pc);

        //
        TemplateConfig tc = new TemplateConfig();
        tc.setXml(null);
        tc.setController(null); // 这里是控制器包名，默认 web
        tc.setEntity(null );
        tc.setXml(null );
        tc.setMapper(null );
        tc.setService(null );
        tc.setServiceImpl(null );
        mpg.setTemplate(tc);
        //
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());

        Map<String, Object> map = freemarkerGen.getEnumMap(id);
        map.put("package_name", pc.getParent());

        // 注入自定义配置，可以在 VM 中使用 cfg.abc 设置的值
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                this.setMap(map);
            }
        };

        List<FileOutConfig> focList = new ArrayList<>();

        /*List<Map> optionDataList = (List<Map>)map.get("optionDataList");
        for(Map enumsMap: optionDataList) {
            focList.add(new FileOutConfig("/templates/generator/enums.java.ftl") {
                @Override
                public String outputFile(TableInfo tableInfo) {
                    cfg.getMap().put("enumsMap", enumsMap);
                    return getGeneratorViewPath(enumsOutputDir, enumsMap.get("className") + ".java");
                }
            });
        }*/
        Map tmptData = (Map)map.get("tmptData");
        focList.add(new FileOutConfig("/templates/generator/enums.java.ftl") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                cfg.getMap().put("enumsMap", tmptData);
                return getGeneratorViewPath(enumsOutputDir, tmptData.get("className") + ".java");
            }
        });

        //enum
        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);
        // 执行生成
        mpg.execute();
    }


    /**
     * 页面生成的文件名
     */
    private static String getGeneratorViewPath(String outputDir, String suffixPath) {
        if (!new File(outputDir).exists()) {
            new File(outputDir).mkdirs();
        }
        String path = outputDir + "/" + suffixPath;
        File viewDir = new File(path).getParentFile();
        if (!viewDir.exists()) {
            viewDir.mkdirs();
        }
        return path;
    }
}
